import 'package:dio/dio.dart';
import 'package:my_desk_flutter/controller/auth_controller.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'auth_interceptor.g.dart';

@riverpod
AuthInterceptor authInterceptor(AuthInterceptorRef ref) {
  final logout = ref.watch(authControllerProvider.notifier).resetLogout;
  return AuthInterceptor(logout);
}

class AuthInterceptor extends Interceptor {
  final Function logout;

  AuthInterceptor(this.logout);

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    super.onResponse(response, handler);
    if (response.data is Map<String, dynamic>) {
      final code = response.data['errorCode'] as int;
      switch (code) {
        case -1001:
          logout();
          break;
        default:
          break;
      }
    }
  }
}
